package cn.lxycx.dataterrace.interceptor.validates;

import cn.lxycx.dataterrace.interceptor.AbsValidateInterceptor;
import cn.lxycx.dataterrace.util.FormValidate;
import cn.lxycx.dataterrace.util.ServletPro;
import com.jfinal.kit.PropKit;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import lxycx.util.validate.Validate.Ret;

import org.apache.log4j.Logger;

import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
/**数据插入校验*/
public class InsertValidate extends AbsValidateInterceptor {
	
	private static Logger log = Logger.getLogger(InsertValidate.class);
	private static String driver = PropKit.get("driver");

	@Override
	public Ret verify(HttpServletRequest req) {

		String sqlid = req.getParameter("sqlid");
		
		if(sqlid!=null){
			//Record re = QueryDao.findByid("data_statement", Integer.parseInt(sqlid),Kv.by("limits like '%IN%'", null));
			Record user = (Record) req.getSession().getAttribute("user");
			String sql1 = "select s.*,l.limits from (select * from data_statement_limit where aid=?) l  left join data_statement s on s.id=l.sid where l.limits like '%IN%' and s.id=? ";
			Record re = Db.findFirst(sql1,user.get("id"),sqlid);
			String valis = null;

			if(re !=null){
				valis = re.getStr("inserts");
				return jsonValidate(req, re, valis);

			}else{
				return new Ret(false, -3, "权限不足");
			}
		}else{
			return new Ret(false, -4, "无效的表");
		}
		
	}
	
	@Override
	protected void render(Controller con) {
		super.render(con);
	}
	
	
	
	public static Ret jsonValidate(HttpServletRequest req,Record re,String jsonstr){
		
		Map<String,String> forms = ServletPro.findParaToMap(req);
		Map<String,String> params = new HashMap<String, String>();

		String tablename = re.get("tablename");
		String aidfield = re.getStr("aidfield");
		String seqstr = re.getStr("seqstr");
		//params.put("id", id);//设置ID
		if(tablename!=null&&aidfield!=null) {
			Ret ret = FormValidate.htmlForm(forms, params, jsonstr,driver);
			if(!params.isEmpty()) {
				if(ret.isFlag()){
					req.setAttribute("tablename", tablename);//设置表名
					req.setAttribute("aidfield", aidfield);
					req.setAttribute("seqstr", seqstr);
					req.setAttribute("params", params);
				}				
				return ret;
			}else {
				return new Ret(false, -6, "请填写修改内容");
			}
		}else {
			return new Ret(false, -5, "缺少主要的配置信息（tablename或aidfield）");
		}
		
	}

	

}
